<template>
  <el-form>
    <el-form-item label="旧密码">
      <el-input v-model.trim="psdForm.oldPsd" />
    </el-form-item>
    <el-form-item label="新密码">
      <el-input v-model.trim="psdForm.newPsd" />
    </el-form-item>
    <el-form-item label="确认密码">
      <el-input v-model.trim="psdForm.comfirmPsd" />
    </el-form-item>
    <el-form-item style="margin-top:15px;">
      <el-button type="primary" :disabled="formFlag" @click="submit">修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { comparePassword } from '@/api/account'

export default {
  props: {
    account: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      psdForm: {
        oldPsd: '',
        newPsd: '',
        comfirmPsd: ''
      }
      // rules: {
      //   oldPsd: [
      //     { required: true, message: '请输入旧密码', trigger: 'blur' }
      //   ],
      //   newPsd: [
      //     { required: true, message: '请输入新密码', trigger: 'blur' }
      //   ],
      //   comfirmPsd: [
      //     { required: true, message: '请再次输入新密码', trigger: 'blur' }
      //   ]
      // }
    }
  },
  computed: {
    formFlag() {
      return this.psdForm.oldPsd === '' || this.psdForm.newPsd === '' || this.psdForm.comfirmPsd === ''
    }
  },
  methods: {
    async submit() {
      const match = await comparePassword({
        account: this.account.account,
        password: this.psdForm.oldPsd
      })
      const confirmFlag = this.confirmPsd()
      if (!match) {
        this.$message({
          type: 'warning',
          message: '旧密码不正确'
        })
        return
      }
      if (!confirmFlag) {
        this.$message({
          type: 'warning',
          message: '新密码两次输入不一致'
        })
        return
      }
      this.$confirm('确定修改帐号密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('update-psd', {
          account: this.account.account,
          password: this.psdForm.comfirmPsd
        })
        this.psdForm = {
          oldPsd: '',
          newPsd: '',
          comfirmPsd: ''
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    confirmPsd() {
      return this.psdForm.newPsd === this.psdForm.comfirmPsd
    }
  }
}
</script>
